package pl.nazaweb.samplesandtutorials.abstracts.contentproviders;

import java.util.HashMap;
import java.util.Map;

import android.net.Uri;
import android.provider.BaseColumns;

public abstract class AbstractTable implements BaseColumns {

	public abstract String getAuthority();

	public abstract Map<String, String> getColumnsWithTypes();

	public String getTableName() {
		return getClass().getSimpleName().toLowerCase();
	}

	public Uri getContentUri() {
		StringBuilder uri = new StringBuilder();
		uri.append("content://").append(getAuthority()).append("/")
				.append(getTableName());
		return Uri.parse(uri.toString());
	}

	public String getContentType() {
		return "vnd.android.cursor.dir/vnd.".concat(getPackageNameWithoutDot())
				.concat(".").concat(getTableName()).concat("_list");
	}

	public String getContentSingleItemType() {
		return "vnd.android.cursor.item/vnd."
				.concat(getPackageNameWithoutDot()).concat(".")
				.concat(getTableName()).concat("_item");
	}

	public String getDefaultSortOrder() {
		return "_id DESC";
	}

	public String getCreateQuery() {
		StringBuilder query = new StringBuilder();
		query.append("CREATE TABLE ").append(getTableName()).append(" ( ")
				.append(_ID).append(" INTEGER PRIMARY KEY ");
		for (Map.Entry<String, String> entry : getColumnsWithTypes().entrySet()) {
			query.append(" , ").append(entry.getKey()).append(" ")
					.append(entry.getValue());
		}
		query.append(" );");
		return query.toString();
	}
	
	public String getDropQuery(){
		return "DROP TABLE IF EXISTS ".concat(getTableName());
	}
	
	public Map<String, String> getProjectionColumns(){
		Map<String, String> columns = new HashMap<String, String>();
		for (Map.Entry<String, String> entry : getColumnsWithTypes().entrySet()) {
			columns.put(entry.getKey().toUpperCase(), entry.getKey().toUpperCase());
		}
		return columns;
	}

	private String getPackageNameWithoutDot() {
		return getClass().getPackage().getName().replace(".", "");
	}
}
